// src/services/product.service.js
import { db } from "../config/sequelize.js";
import { Op } from "sequelize";
import { NotFoundError, BadRequestError } from "../utils/errors.js";

export class ProductService {
  constructor(db) {
    if (!db || !db.models) {
      throw new Error("必须提供有效的 Sequelize 实例");
    }
    this.db = db;
    this.Product = db.models.Product;
    this.Category = db.models.Category;
    this.SpecType = db.models.SpecType;
    this.SkuSpec = db.models.SkuSpec;
    this.SpecValue = db.models.SpecValue;
    this.Sku = db.models.Sku;
    this.Op = db.sequelize.Op;
    // 验证模型方法是否可用
    // 调试日志
    console.log("Product 模型验证:", {
      isModel: typeof this.Product === "function",
      hasFindAll: "findAll" in this.Product,
    });
    // 商品字段定义
    this.ADMIN_ATTRIBUTES = [
      "id",
      "name",
      "slug",
      "description",
      "price",
      "costPrice",
      "stock",
      "sku",
      "images",
      "spec",
      "status",
      "isFeatured",
      "salesCount",
      "viewCount",
      "category_id",
      "metaTitle",
      "metaDescription",
      "createdAt",
      "updatedAt",
    ];

    this.PUBLIC_ATTRIBUTES = [
      "id",
      "name",
      "slug",
      "price",
      "images",
      "salesCount",
      "category_id",
    ];
  }

  /**
   * 获取商品分类列表
   */
  async getCategoryList() {
    const categories = await this.Category.findAll({
      attributes: ["id", "name", "slug", "parentId"],
      where: { status: "active" },
      sortOrder: [["order", "ASC"]],
    });

    return categories;
  }

  /**
   * 获取商品列表（支持分页、筛选和排序）
   * @param {Object} options - 查询选项
   * @param {Object} options.where - 筛选条件
   * @param {number} options.page - 页码（默认1）
   * @param {number} options.limit - 每页条数（默认10）
   * @param {Array} options.order - 排序规则
   * @param {boolean} options.isAdmin - 是否管理员权限
   * @returns {Promise<{data: Array, pagination: Object}>}
   */
  async getProductList({
    where = {},
    page = 1,
    limit = 10,
    order = [["createdAt", "DESC"]],
    isAdmin = false,
    withSkus = false, // 新增参数控制是否加载SKU
  }) {
    // 1. 设置返回字段
    const attributes = isAdmin ? this.ADMIN_ATTRIBUTES : this.PUBLIC_ATTRIBUTES;

    // 2. 构建查询条件
    const sanitizedWhere = this._buildWhereClause(where);

    // 3. 构建关联查询（统一管理include）
    const include = isAdmin
      ? [
          {
            model: this.Category,
            as: "category",
            attributes: ["id", "name"],
          },
        ]
      : [];

    // 需要SKU数据时添加关联
    if (withSkus) {
      include.push({
        model: this.Sku,
        as: "productSkus",
        attributes: ["id", "price", "stock", "image", "sku_name"],
        include: [
          {
            model: this.SpecValue,
            as: "specValue",
            attributes: ["id", "value"],
            include: [
              {
                model: this.SpecType,
                as: "specType",
                attributes: ["id", "name"],
              },
            ],
          },
        ],
      });
    }
    // 3. 执行分页查询
    const { count, rows } = await this.Product.findAndCountAll({
      where: sanitizedWhere,
      attributes,
      include,
      order,
      limit: Number(limit),
      offset: (page - 1) * limit,
      paranoid: true, // 不包含软删除的记录
    });

    // 5. 处理SKU数据格式（可选）
    const processedData = rows.map((product) => {
      const plainProduct = product.get({ plain: true });
      return {
        ...plainProduct,
        skus: plainProduct.productSkus?.map((sku) => {
          // 先提取需要的specs数据
          const specs =
            sku.specValues?.map((sv) => ({
              spec_id: sv.specType?.id,
              spec_name: sv.specType?.name,
              sku_name: sv.sku_name || "默认",
              spec_value_id: sv.id,
              value: sv.value,
            })) || [];

          // 返回新的SKU对象，只包含需要的字段
          return {
            id: sku.id,
            price: sku.price,
            stock: sku.stock,
            sku_name: sku.sku_name || "默认",
            image: sku.image,
            specs: specs,
          };
        }),
        productSkus: undefined, // 移除原始字段
      };
    });

    return {
      data: processedData,
      pagination: {
        total: count,
        page: Number(page),
        limit: Number(limit),
        totalPages: Math.ceil(count / limit),
      },
    };
  }

  /**
   * 构建安全的WHERE条件
   * @private
   */
  _buildWhereClause(filters = {}) {
    const { search, status, category_id, minPrice, maxPrice } = filters;
    const where = {};

    // 多字段模糊搜索
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } },
        { sku: { [Op.like]: `%${search}%` } },
      ];
    }

    // 精确匹配字段
    if (status) where.status = status;
    if (category_id) where.category_id = category_id;

    // 价格范围
    if (minPrice || maxPrice) {
      where.price = {};
      if (minPrice) where.price[Op.gte] = minPrice;
      if (maxPrice) where.price[Op.lte] = maxPrice;
    }

    return where;
  }

  /**
   * 获取商品详情
   * @param {number|string} productId - 商品ID
   * @param {boolean} isAdmin - 是否管理员权限
   */
  async getProductById(productId, isAdmin = false) {
    const attributes = isAdmin ? this.ADMIN_ATTRIBUTES : this.PUBLIC_ATTRIBUTES;

    const product = await this.Product.findOne({
      where: { id: productId },
      attributes,
      include: [
        {
          model: this.Category,
          as: "category",
          attributes: ["id", "name", "slug"],
        },
      ],
      paranoid: !isAdmin, // 管理员可以查看已删除的商品
    });

    if (!product) {
      throw new NotFoundError("商品不存在");
    }

    // 增加浏览量
    if (!isAdmin) {
      await this.incrementViewCount(productId);
    }

    return product;
  }

  /**
   * 检查SKU是否已存在
   * @param {string} sku - SKU编码
   * @param {number} [excludeId] - 需要排除的商品ID（用于更新操作）
   */
  async checkSkuExists(sku, excludeId = null) {
    const where = { sku };
    if (excludeId) {
      where.id = { [Op.ne]: excludeId };
    }

    const exists = await this.Product.findOne({ where });
    return !!exists;
  }

  /**
   * 创建商品
   * @param {Object} productData - 商品数据
   */
  async createProduct(productData) {
    // 验证必填字段
    if (!productData.name || !productData.category_id) {
      throw new BadRequestError("商品名称和分类是必填字段");
    }

    // 2. 验证分类是否存在
    await this.Category.validateExists(productData.category_id);
    // 生成或使用提供的 slug
    const slug = productData.slug || this._generateSlug(productData.name);

    // 检查 slug 是否已存在
    const slugExists = await this.Product.findOne({
      where: { slug },
    });

    if (slugExists) {
      throw new BadRequestError("商品别名已存在,请更改");
    }
    // 3. 处理图片数据
    if (productData.images && !Array.isArray(productData.images)) {
      productData.images = [productData.images];
    }

    // 4. 处理SKU数据
    if (productData.skus && productData.skus.length > 0) {
      this._validateSkus(productData.skus);
    } else {
      // 如果没有SKU，则使用商品基础价格和库存
      if (!productData.price || productData.price <= 0) {
        throw new BadRequestError("商品价格必须大于0");
      }
      productData.skus = [
        {
          price: productData.price,
          stock: productData.stock || 0,
          specs: [], // 无规格的默认SKU
        },
      ];
    }

    // 5. 使用事务保存数据
    const transaction = await db.sequelize.transaction();

    try {
      // 保存商品基础信息
      const product = await this.Product.create(
        {
          name: productData.name,
          category_id: productData.category_id,
          description: productData.description || "",
          price: productData.price || 0, // 保留基础价格字段
          stock: productData.stock || 0, // 保留基础库存字段
          images: productData.images || [],
          thumbnail: productData.thumbnail || "",
          status: productData.status || "draft",
          spec: productData.spec || {},
          slug: productData.slug || this._generateSlug(productData.name),
        },
        { transaction }
      );
      console.log("productData:", productData);
      // 保存SKU及规格关联
      await this._createProductSkus(product.id, productData.skus, transaction);

      await transaction.commit();
      return product;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  /**
   * 更新商品信息
   * @param {number} productId - 商品ID
   * @param {Object} updateData - 更新数据
   */
  async updateProduct(productId, updateData) {
    // 输入验证
    if (!updateData || Object.keys(updateData).length === 0) {
      throw new BadRequestError("更新数据不能为空");
    }
    const transaction = await this.db.sequelize.transaction();

    if (updateData.slug) {
      const exists = await this.Product.findOne({
        where: { slug: updateData.slug, id: { [Op.ne]: productId } },
        transaction,
      });
      if (exists) throw new BadRequestError("商品别名已存在");
    }
    try {
      // 1. 检查商品SKU唯一性
      if (updateData.sku) {
        const exists = await this.Product.findOne({
          where: {
            sku: updateData.sku,
            id: { [Op.ne]: productId },
          },
          transaction,
        });
        if (exists) throw new BadRequestError("SKU已存在");
      }

      // 2. 加载商品及SKUs（使用正确别名）
      const product = await this.Product.findByPk(productId, {
        transaction,
        lock: true,
        include: [
          {
            model: this.Sku,
            as: "productSkus", // 必须与模型定义一致
          },
        ],
      });

      if (!product) throw new NotFoundError("商品不存在");

      // 3. 更新商品基础信息
      const updatableFields = Object.keys(updateData).filter(
        (key) => !["skus", "productSkus"].includes(key)
      );

      if (updatableFields.length > 0) {
        await product.update(updateData, {
          fields: updatableFields,
          transaction,
        });
      }

      // 4. 处理SKU更新
      if (updateData.skus) {
        await this._updateSkus(product, updateData.skus, transaction);
      }

      // 5. 提交事务
      await transaction.commit();

      // 返回最新数据
      return this.getProductById(productId, true);
    } catch (error) {
      // 安全回滚
      if (transaction && !transaction.finished) {
        await transaction.rollback();
      }
      if (error.name === "SequelizeUniqueConstraintError") {
        throw new BadRequestError("商品别名或SKU编码已存在");
      }
      console.error("商品更新失败:", error);
      throw error;
    }
  }

  /**
   * 增加商品浏览量
   * @param {number} productId - 商品ID
   */
  async incrementViewCount(productId) {
    await this.Product.increment("viewCount", {
      where: { id: productId },
      by: 1,
    });
  }

  /**
   * 批量删除商品
   * @param {Array} productIds - 商品ID数组
   * @param {boolean} force - 是否强制删除（false为软删除）
   */
  async batchDeleteProducts(productIds, force = false) {
    // 验证输入
    if (!Array.isArray(productIds)) {
      throw new BadRequestError("productIds 必须是一个数组");
    }

    if (productIds.length === 0) {
      throw new BadRequestError("productIds 不能为空");
    }

    // 检查所有商品是否存在
    const existingProducts = await this.Product.findAll({
      where: {
        id: {
          [Op.in]: productIds,
        },
      },
      paranoid: false, // 包括已软删除的记录
    });

    if (existingProducts.length !== productIds.length) {
      const foundIds = existingProducts.map((product) => product.id);
      const missingIds = productIds.filter((id) => !foundIds.includes(id));
      throw new NotFoundError(`以下商品不存在: ${missingIds.join(", ")}`);
    }

    // 执行批量删除
    try {
      const result = await this.Product.destroy({
        where: {
          id: {
            [Op.in]: productIds,
          },
        },
        force: force,
      });

      return {
        deletedCount: result,
      };
    } catch (error) {
      console.error("批量删除商品失败:", error);
      throw new Error("批量删除商品失败");
    }
  }

  /**
   * 删除商品（软删除）
   * @param {number} productId - 商品ID
   */
  async deleteProduct(productId) {
    const product = await this.Product.findByPk(productId);
    if (!product) {
      throw new NotFoundError("商品不存在");
    }

    // 检查是否有订单关联
    const hasOrders = await this.db.OrderItem.count({
      where: { productId },
    });

    if (hasOrders > 0) {
      throw new BadRequestError("该商品已有订单记录，不能删除");
    }

    return await product.destroy();
  }

  /**
   * 恢复已删除的商品
   * @param {number} productId - 商品ID
   */
  async restoreProduct(productId) {
    const product = await this.Product.findOne({
      where: { id: productId },
      paranoid: false,
    });

    if (!product) {
      throw new NotFoundError("商品不存在");
    }

    if (!product.deletedAt) {
      throw new BadRequestError("商品未被删除");
    }

    return await product.restore();
  }

  /**
   * 更新商品状态
   * @param {number} productId - 商品ID
   * @param {string} status - 新状态（draft/published/archived）
   */
  async updateProductStatus(productId, status) {
    const validStatuses = ["draft", "published", "archived"];
    if (!validStatuses.includes(status)) {
      throw new BadRequestError("无效的商品状态");
    }

    const product = await this.Product.findByPk(productId);
    if (!product) {
      throw new NotFoundError("商品不存在");
    }

    return await product.update({ status });
  }

  /**
   * 获取关联商品（同分类下的其他商品）
   * @param {number} productId - 商品ID
   * @param {number} [limit=4] - 返回数量限制
   */
  async getRelatedProducts(productId, limit = 4) {
    const product = await this.Product.findByPk(productId, {
      attributes: ["category_id"],
    });

    if (!product || !product.category_id) return [];

    return this.Product.findAll({
      where: {
        category_id: product.category_id,
        id: { [Op.ne]: productId },
        status: "published",
      },
      limit,
      order: this.db.sequelize.random(),
      attributes: this.PUBLIC_ATTRIBUTES,
    });
  }

  /**
   * 获取所有规格类型列表及其对应的规格值
   * @param {number} id - 商品分类ID
   * @param {Object} options - 分页和搜索选项
   * @param {number} options.page - 当前页码
   * @param {number} options.limit - 每页条数
   * @param {string} options.keyword - 搜索关键字
   * @returns {Promise<Object>} 返回分页数据，包含规格类型及其规格值
   */
  async getSpecTypeList(id, { page = 1, limit = 10, keyword = "" }) {
    // 调用SpecType模型的findAll方法，查询所有规格类型并返回
    try {
      // 校验商品分类id是否存在
      const category = await this.Category.findByPk(id);
      if (!category) {
        throw new NotFoundError("商品分类不存在");
      }

      // 1. 构建查询条件
      const where = {};
      if (keyword) {
        where.name = {
          [this.Op.like]: `%${keyword}%`,
        };
      }

      // 2. 执行分页查询
      const { count, rows } = await this.SpecType.findAndCountAll({
        where,
        limit: Number(limit),
        offset: (page - 1) * limit,
        order: [["createdAt", "DESC"]], // 按创建时间倒序
        include: [
          {
            model: this.SpecValue, // 关联 SpecValue 模型
            attributes: ["id", "value"], // 只返回 id 和 value 字段
            as: "specValues", // 关联别名（取决于你的模型定义）
          },
        ],
      });

      // 3. 返回分页结构
      return {
        list: rows,
        pagination: {
          total: count,
          page: Number(page),
          pageSize: Number(limit),
          totalPages: Math.ceil(count / limit),
        },
      };
    } catch (error) {
      console.error("获取规格类型列表失败：", error);
      throw error;
    }
  }

  /**
   * 创建规格类型的方法
   * @param {string} specTypeName - 规格类型的名称
   * @returns {Promise} - 返回一个Promise对象，用于异步操作
   */
  async createSpecType(categoryId, specTypeName, values, description) {
    console.log("创建规格类型：", specTypeName, values, description);
    try {
      // 验证规格类型名称是否已存在
      const existingSpecType = await this.SpecType.findOne({
        where: { name: specTypeName },
        category_id: categoryId, // 增加分类ID条件
      });
      if (existingSpecType) {
        throw new BadRequestError("规格类型名称已存在");
      }

      // 开启事务确保数据一致性
      const result = await db.sequelize.transaction(async (transaction) => {
        // 1. 创建规格类型
        const specType = await this.SpecType.create(
          {
            name: specTypeName,
            description,
          },
          { transaction }
        );

        // 2. 创建关联的规格值
        if (values && values.length > 0) {
          const specValuesToCreate = values.map((value) => ({
            spec_type_id: specType.id,
            value: typeof value === "string" ? value : value.value,
            // 可以添加其他字段如sort_order等
            ...(typeof value === "object" ? value : {}),
          }));

          await this.SpecValue.bulkCreate(specValuesToCreate, { transaction });
        }

        return specType;
      });

      return result;
    } catch (error) {
      console.error("创建规格类型失败：", error);
      throw error;
    }
  }

  /**
   * 更新规格类型及其关联的规格值
   * @param {number} specTypeId - 规格类型ID
   * @param {string} specTypeName - 规格类型名称
   * @param {string} description - 规格类型描述
   * @param {Array<string|object>} values - 规格值数组
   * @returns {Promise<SpecType>} - 更新后的规格类型
   */
  async updateSpecType(specTypeId, specTypeName, values, description) {
    console.log("更新规格类型", specTypeId, specTypeName, values, description);
    if (!specTypeId) {
      throw new BadRequestError("规格类型ID不能为空");
    }

    try {
      return await db.sequelize.transaction(async (transaction) => {
        // 1. 查找并更新规格类型
        const specType = await this.SpecType.findByPk(specTypeId, {
          transaction,
        });
        if (!specType) {
          throw new NotFoundError("规格类型不存在");
        }

        // 检查名称是否被其他规格类型使用
        if (specTypeName && specTypeName !== specType.name) {
          const existing = await this.SpecType.findOne({
            where: {
              name: specTypeName,
              category_id: specType.category_id,
              id: { [Op.ne]: specTypeId },
            },
            transaction,
          });
          if (existing) {
            throw new BadRequestError("规格类型名称已被使用");
          }
        }

        // 更新规格类型基本信息
        await specType.update(
          {
            name: specTypeName,
            description,
          },
          { transaction }
        );

        // 2. 处理规格值
        if (values && Array.isArray(values)) {
          // 获取现有的规格值
          const existingValues = await this.SpecValue.findAll({
            where: { spec_type_id: specTypeId },
            transaction,
          });

          // 将新值转换为统一格式
          const newValues = values.map((v) => ({
            value: typeof v === "string" ? v : v.value,
            id: typeof v === "object" ? v.id : null,
            sort_order: typeof v === "object" ? v.sort_order || 0 : 0,
          }));

          // 找出需要删除的值（存在于数据库但不在新值中）
          const valuesToRemove = existingValues.filter(
            (ev) => !newValues.some((nv) => nv.value === ev.value)
          );
          if (valuesToRemove.length > 0) {
            await this.SpecValue.destroy({
              where: {
                id: valuesToRemove.map((v) => v.id),
              },
              transaction,
            });
          }

          // 找出需要添加的值（不存在于数据库中）
          const valuesToAdd = newValues.filter(
            (nv) => !existingValues.some((ev) => ev.value === nv.value)
          );
          if (valuesToAdd.length > 0) {
            await this.SpecValue.bulkCreate(
              valuesToAdd.map((v) => ({
                spec_type_id: specTypeId,
                value: v.value,
                // 可以添加其他字段
                sort_order: v.sort_order || 0,
              })),
              { transaction }
            );
          }

          // 找出需要更新的值（存在于两者中）
          const valuesToUpdate = existingValues.filter((ev) =>
            newValues.some(
              (nv) =>
                nv.value === ev.value &&
                nv.sort_order !== undefined &&
                nv.sort_order !== ev.sort_order
            )
          );
          if (valuesToUpdate.length > 0) {
            await Promise.all(
              valuesToUpdate.map((ev) => {
                const newVal = newValues.find((nv) => nv.value === ev.value);
                return this.SpecValue.update(
                  { sort_order: newVal.sort_order },
                  { where: { id: ev.id }, transaction }
                );
              })
            );
          }
        }

        // 重新加载关联数据
        return this.SpecType.findByPk(specTypeId, {
          include: [
            {
              model: this.SpecValue,
              as: "specValue",
            },
          ],
          transaction,
        });
      });
    } catch (error) {
      console.error("更新规格类型失败：", error);
      throw error;
    }
  }
  /**
   * 删除规格类型
   * @param {number} specTypeId 规格类型ID
   * @returns {Promise<void>} 删除结果
   */
  async deleteSpecType(specTypeId) {
    if (!specTypeId) {
      throw new BadRequestError("规格类型ID不能为空");
    }
    try {
      const specType = await this.SpecType.findByPk(specTypeId);
      if (!specType) {
        throw new NotFoundError("规格类型不存在");
      }

      // 删除规格类型
      await specType.destroy();
    } catch (error) {
      console.error("删除规格类型失败：", error);
      throw error;
    }
  }

  /**
   * 获取SKU详情
   * @param productId 商品ID
   */
  async getSkuById(productId, isAdmin) {
    console.log("商品id:", productId, isAdmin);
    const skus = await this.Sku.findAll({
      where: { product_id: productId },
      include: [
        {
          model: this.SkuSpec,
          as: "skuSpecs",
          include: [
            {
              model: this.SpecValue,
              as: "specValue",
              attributes: ["id", "value"],
              include: [
                {
                  model: this.SpecType,
                  as: "specType",
                  attributes: ["id", "name"],
                },
              ],
            },
          ],
        },
      ],
      order: [["created_at", "ASC"]], // 按创建时间排序
    });
    return skus.map((sku) => {
      const plainSku = sku.get({ plain: true });

      const specs = (() => {
        if (!plainSku.skuSpecs) return isAdmin ? {} : [];

        return isAdmin==='1'
          ? plainSku.skuSpecs.map((spec) => ({
              spec_id: spec.specValue?.specType?.id,
              spec_name: spec.specValue?.specType?.name,
              spec_value_id: spec.specValue?.id,
              value: spec.specValue?.value,
            }))
          : plainSku.skuSpecs.reduce((acc, spec) => {
              const specValue = spec.specValue || {};
              const specType = specValue.specType || {};
              if (specType.name && specValue.value) {
                acc[specType.name] = specValue.value;
              }
              return acc;
            }, {});
      })();

      return {
        id: plainSku.id,
        sku_name: plainSku.sku_name,
        price: plainSku.price,
        stock: plainSku.stock,
        image: plainSku.image,
        specs: specs || [], // 默认空对象
      };
    });
  }


  /**
   * 获取指定产品的规格信息
   * @param {number} productId - 产品ID
   * @returns {Promise<Object>} 返回处理后的产品规格信息
   */
  async getProductSpecs(productId) {
    console.log("获取产品规格信息：", productId);

    // 通过SKU获取规格信息
    const skus = await this.Sku.findAll({
      where: { product_id: productId },
      include: [
        {
          model: this.SkuSpec,
          as: "skuSpecs",
          include: [
            {
              model: this.SpecValue,
              as: "specValue",
              include: [
                {
                  model: this.SpecType,
                  as: "specType",
                },
              ],
            },
          ],
        },
      ],
    });
    // 处理数据格式
    const specMap = new Map();

    skus.forEach((sku) => {
      // 检查sku.skuSpecs是否存在且是数组
      if (sku.skuSpecs && Array.isArray(sku.skuSpecs)) {
        sku.skuSpecs.forEach((skuSpec) => {
          // 检查必要的嵌套对象是否存在
          if (skuSpec && skuSpec.specValue && skuSpec.specValue.specType) {
            const specType = skuSpec.specValue.specType;
            const specValue = skuSpec.specValue;

            if (!specMap.has(specType.id)) {
              specMap.set(specType.id, {
                name: specType.name,
                values: new Set(),
                images: {},
              });
            }

            const specInfo = specMap.get(specType.id);
            specInfo.values.add(specValue.value);

            if (specValue.image) {
              specInfo.images[specValue.value] = specValue.image;
            }
          } else {
            console.warn("缺少规格值或规格类型数据:", skuSpec);
          }
        });
      } else {
        console.warn("SKU缺少规格数据:", sku.id);
      }
    });

    return Array.from(specMap.values()).map((spec) => ({
      name: spec.name,
      values: Array.from(spec.values),
      images: spec.images,
    }));
  }

  /**
   * 获取商品下的所有SKU
   * @param productId 商品ID
   */
  static async getSkusByProductId(productId) {
    return await SkuModel.find({ productId }).sort({ createdAt: -1 });
  }

  /**
   * 删除SKU
   * @param id SKU ID
   */
  static async deleteSku(id) {
    const result = await SkuModel.findByIdAndDelete(id);

    if (!result) {
      throw new NotFoundError("SKU不存在");
    }
  }

  // 私有方法：验证SKU数据
  _validateSkus(skus) {
    if (!Array.isArray(skus)) {
      throw new BadRequestError("SKU数据必须是数组");
    }

    const skuCodes = new Set();

    skus.forEach((sku) => {
      if (!sku.price || sku.price <= 0) {
        throw new BadRequestError("SKU价格必须大于0");
      }

      // 生成SKU编码并检查唯一性
      const skuCode = this._generateSkuCode(sku.specs || []);
      console.log("skuCodes:", skuCodes);
      console.log("skuCode:", skuCode);
      if (skuCodes.has(skuCode)) {
        throw new BadRequestError(`重复的SKU组合: ${skuCode}`);
      }
      skuCodes.add(skuCode);
    });
  }

  // 私有方法：创建SKU及规格关联
  async _createProductSkus(productId, skus, transaction) {
    console.log("productId:", productId);
    console.log("skus:", skus);
    for (const skuData of skus) {
      console.log("skuData:", skuData);
      const sku = await this.Sku.create(
        {
          product_id: productId,
          price: skuData.price,
          spec_name: skuData.spec_name,
          sku_name: skuData.sku_name,
          stock: skuData.stock || 0,
          image: skuData.image || null,
          sku_code: this._generateSkuCode(skuData.specs),
          specs: skuData.specs,
        },
        { transaction }
      );
      console.log("skuData.specs:", skuData.specs);
      console.log(
        "即将插入 sku_spec 的数据:",
        sku.specs.map((spec) => ({
          sku_id: sku.id,
          spec_type_id: spec.spec_type_id,
          spec_value_id: spec.spec_value_id,
          value: spec.value,
        }))
      );
      // 保存规格关联
      if (skuData.specs && skuData.specs.length > 0) {
        await this.SkuSpec.bulkCreate(
          skuData.specs.map((spec) => ({
            sku_id: sku.id,
            spec_type_id: Number(spec.spec_type_id), // 需确保前端传入 specId
            spec_value_id: spec.spec_value_id, // 需确保传入值 ID
            value: spec.value,
          })),
          { transaction }
        );
      }
    }
  }
  // 私有方法：生成SKU编码
  _generateSkuCode(specs = []) {
    // 提取所有规格值（如 ["12+256G", "红色"]）
    const specValues = specs.map((spec) => {
      const keys = Object.keys(spec);
      // 取最后一个键的值（避免 "版本":"版本" 这类冗余数据）
      return spec[keys[keys.length - 1]];
    });

    // 按字母排序后拼接
    const specPart = specValues.sort().join("-");
    console.log("生成结果:", `SKU-${Date.now()}-${specPart || "BASE"}`);
    return `SKU-${Date.now()}-${specPart || "BASE"}`;
  }

  // 私有方法：生成slug
  _generateSlug(name) {
    return name
      .toLowerCase()
      .replace(/[^\w\s]/gi, "")
      .replace(/\s+/g, "-");
  }

  // 私有方法：更新商品SKU
  async _updateSkus(product, newSkus, transaction) {
    const existingSkus = await this.Sku.findAll({
      where: { product_id: product.id },
      transaction,
      include: [{ model: this.SkuSpec, as: "skuSpecs" }], // 加载关联的规格
    });
    // 分类处理SKU
    const toCreate = newSkus.filter((s) => !s.id);
    const toUpdate = newSkus.filter(
      (s) => s.id && existingSkus.some((es) => es.id === s.id)
    );
    const toDeleteIds = existingSkus
      .filter((es) => !newSkus.some((s) => s.id === es.id))
      .map((es) => es.id);

    // 1. 删除废弃的SKU及关联规格
    if (toDeleteIds.length > 0) {
      await this.SkuSpec.destroy({
        where: { sku_id: { [Op.in]: toDeleteIds } },
        transaction,
      });
      await this.Sku.destroy({
        where: { id: { [Op.in]: toDeleteIds } },
        transaction,
      });
    }

    // 2. 更新现有SKU
    for (const skuData of toUpdate) {
      const sku = existingSkus.find((s) => s.id === skuData.id);
      await sku.update(
        {
          price: skuData.price,
          stock: skuData.stock,
          image: skuData.image,
          sku_name: skuData.sku_name,
          specs: skuData.specs, // 更新JSON字段
        },
        { transaction }
      );

      // 更新规格关联（先删后增）
      await this.SkuSpec.destroy({
        where: { sku_id: sku.id },
        transaction,
      });
      await this.SkuSpec.bulkCreate(
        skuData.specs.map((spec) => ({
          sku_id: sku.id,
          spec_type_id: spec.spec_type_id,
          spec_value_id: spec.spec_value_id,
          value: spec.value,
        })),
        { transaction }
      );
    }

    // 3. 新增SKU
    if (toCreate.length > 0) {
      await this._createProductSkus(product.id, toCreate, transaction);
    }
  }
}
